import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;

public class ProducerConsumer {
    private static final int BUFFER_SIZE = 5; // 缓冲区大小

    private static Queue<String> buffer = new LinkedList<>(); // 缓冲区

    // 生产者线程
    private static class Producer implements Runnable {
        @Override
        public void run() {
            try {
                while (true) {
                    synchronized (buffer) {
                        // 如果缓冲区已满，生产者等待
                        while (buffer.size() >= BUFFER_SIZE) {
                            buffer.wait();
                        }
                        // 生产产品
                        String product = "产品" + new Random().nextInt(10);
                        buffer.offer(product);
                        System.out.println("Producer put: " + product);
                        // 通知消费者可以消费了
                        buffer.notifyAll();
                    }
                    // 模拟生产过程的延迟
                    Thread.sleep(new Random().nextInt(1000));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 消费者线程
    private static class Consumer implements Runnable {
        @Override
        public void run() {
            try {
                while (true) {
                    synchronized (buffer) {
                        // 如果缓冲区为空，消费者等待
                        while (buffer.isEmpty()) {
                            buffer.wait();
                        }
                        // 消费产品
                        String product = buffer.poll();
                        System.out.println("Consumer get: " + product);
                        // 通知生产者可以生产了
                        buffer.notifyAll();
                    }
                    // 模拟消费过程的延迟
                    Thread.sleep(new Random().nextInt(1000));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        Thread producerThread = new Thread(new Producer()); // 生产者线程
        Thread consumerThread = new Thread(new Consumer()); // 消费者线程

        producerThread.start();
        consumerThread.start();
    }
}
